package com.neu.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.neu.common.GoodsAllinone;
import com.neu.domain.ShoppingBrand;
import com.neu.domain.ShoppingCategory;
import com.neu.domain.ShoppingGoods;
import com.neu.domain.ShoppingGoodsAttribute;
import com.neu.domain.ShoppingGoodsProduct;
import com.neu.domain.ShoppingGoodsSpecification;
import com.neu.util.ResponseUtil;
import com.neu.vo.CatVo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.neu.util.AdminResponseCode.GOODS_NAME_EXIST;

@Service
public class AdminGoodsService {
    private final Log logger = LogFactory.getLog(AdminGoodsService.class);

    @Autowired
    private ShoppingGoodsService goodsService;
    @Autowired
    private ShoppingGoodsSpecificationService specificationService;
    @Autowired
    private ShoppingGoodsAttributeService attributeService;
    @Autowired
    private ShoppingGoodsProductService productService;
    @Autowired
    private ShoppingCategoryService categoryService;
    @Autowired
    private ShoppingBrandService brandService;

   
/**
 * 分页获取商品列表
 * @param goodsSn
 * @param name
 * @param page
 * @param limit
 * @param sort
 * @param order
 * @return
 */
   //list 方法
    public Object list (String goodsSn, String name, Integer page, Integer limit, String sort, String order){
    	List<ShoppingGoods> ge = goodsService.querySelective(goodsSn, name, page, limit, sort, order);	
    	return ResponseUtil.okList(ge);
    }
    //list02
    public Object list2 () {
    	
        List<ShoppingCategory> l1CatList = categoryService.queryL1();
        List<CatVo> categoryList = new ArrayList<>(l1CatList.size());

        for (ShoppingCategory l1 : l1CatList) {
            CatVo l1CatVo = new CatVo();
            l1CatVo.setValue(l1.getId());
            l1CatVo.setLabel(l1.getName());

            List<ShoppingCategory> l2CatList = categoryService.queryByPid(l1.getId());
            List<CatVo> children = new ArrayList<>(l2CatList.size());
            for (ShoppingCategory l2 : l2CatList) {
                CatVo l2CatVo = new CatVo();
                l2CatVo.setValue(l2.getId());
                l2CatVo.setLabel(l2.getName());
                children.add(l2CatVo);
            }
            l1CatVo.setChildren(children);

            categoryList.add(l1CatVo);
        }

        List<ShoppingBrand> list = brandService.all();
        List<Map<String, Object>> brandList = new ArrayList<>(l1CatList.size());
        for (ShoppingBrand brand : list) {
            Map<String, Object> b = new HashMap<>(2);
            b.put("value", brand.getId());
            b.put("label", brand.getName());
            brandList.add(b);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", categoryList);
        data.put("brandList", brandList);
        return ResponseUtil.ok(data);
    }
    /**
     * 编辑商品
     * <p>
     * TODO
     * 目前商品修改的逻辑是
     * 1. 更新Shopping_goods表
     * 2. 逻辑删除Shopping_goods_specification、Shopping_goods_attribute、Shopping_goods_product
     * 3. 添加Shopping_goods_specification、Shopping_goods_attribute、Shopping_goods_product
     * <p>
     * 这里商品三个表的数据采用删除再添加的策略是因为
     * 商品编辑页面，支持管理员添加删除商品规格、添加删除商品属性，因此这里仅仅更新是不可能的，
     * 只能删除三个表旧的数据，然后添加新的数据。
     * 但是这里又会引入新的问题，就是存在订单商品货品ID指向了失效的商品货品表。
     * 因此这里会拒绝管理员编辑商品，如果订单或购物车中存在商品。
     * 所以这里可能需要重新设计。
     */
    //update
    public Object update(GoodsAllinone goodsAllinone) {
    	ShoppingGoods goods = goodsAllinone.getGoods();
    	System.out.println("11");
    	if (goodsService.updateById(goods) == 0) {
            throw new RuntimeException("更新数据失败");
        }
    	int gid =goods.getId();
    	specificationService.deleteByGid(gid);
    	attributeService.deleteByGid(gid);
    	productService.deleteByGid(gid);
    	System.out.println("22");
    	ShoppingGoodsSpecification[]  goodsSpecification = goodsAllinone.getSpecifications();
    	 for (ShoppingGoodsSpecification specification : goodsSpecification) {
             specification.setGoodsId(goods.getId());
             System.out.println("33");
             specificationService.add(specification);
         }
    	 ShoppingGoodsAttribute[] goodsAttribute =goodsAllinone.getAttributes();
    	 for (ShoppingGoodsAttribute attribute : goodsAttribute) {
			attribute.setGoodsId(goods.getId());
			 System.out.println("44");
			attributeService.add(attribute);
		}
    	ShoppingGoodsSpecification[] goodsSpecifications = goodsAllinone.getSpecifications();
    	for (ShoppingGoodsSpecification specification : goodsSpecifications) {
			specification.setGoodsId(goods.getId());
			 System.out.println("55");
			specificationService.add(specification);	
		}
        return ResponseUtil.ok();
    }
    //delect
    public Object delete(ShoppingGoods goods) {
    	Integer id = goods.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        Integer gid = goods.getId();
        goodsService.deleteById(gid);
        specificationService.deleteByGid(gid);
        attributeService.deleteByGid(gid);
        productService.deleteByGid(gid);
        return ResponseUtil.ok();
    	
    }
    //create
    public Object create(GoodsAllinone goodsAllinone) {
        ShoppingGoods goods = goodsAllinone.getGoods();
        ShoppingGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        ShoppingGoodsSpecification[] specifications = goodsAllinone.getSpecifications();
        ShoppingGoodsProduct[] products = goodsAllinone.getProducts();

        String name = goods.getName();
        if (goodsService.checkExistByName(name)) {
            return ResponseUtil.fail(GOODS_NAME_EXIST, "商品名已经存在");
        }
        goodsService.add(goods);
        String url="Test";
        if (!StringUtils.isEmpty(url)) {
            goods.setShareUrl(url);
            if (goodsService.updateById(goods) == 0) {
                throw new RuntimeException("更新数据失败");
            }
        }
        for (ShoppingGoodsSpecification specification : specifications) {
            specification.setGoodsId(goods.getId());
            specificationService.add(specification);
        }
        for (ShoppingGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attributeService.add(attribute);
        }
        for (ShoppingGoodsProduct product : products) {
            product.setGoodsId(goods.getId());
            productService.add(product);
        }
        return ResponseUtil.ok();
    }
    //detail查询信息
    public Object detail(Integer id) {
        ShoppingGoods goods = goodsService.findById(id);
        List<ShoppingGoodsProduct> products = productService.queryByGid(id);
        List<ShoppingGoodsSpecification> specifications = specificationService.queryByGid(id);
        List<ShoppingGoodsAttribute> attributes = attributeService.queryByGid(id);
        Integer categoryId = goods.getCategoryId();
        ShoppingCategory category = categoryService.findById(categoryId);
        Integer[] categoryIds = new Integer[]{};
        if (category != null) {
            Integer parentCategoryId = category.getPid();
            categoryIds = new Integer[]{parentCategoryId, categoryId};
        }
        Map<String, Object> data = new HashMap<>();
        data.put("goods", goods);
        data.put("specifications", specifications);
        data.put("products", products);
        data.put("attributes", attributes);
        data.put("categoryIds", categoryIds);
        return ResponseUtil.ok(data);
    }

}
